#!/usr/bin/env python3
# -*- coding: utf-8 -*-

def validate_anonymous_uci_file(file_path):
    """验证匿名session格式的UCI配置文件"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        lines = content.splitlines()
        config_count = content.count("config 'apn'")
        option_count = content.count("option ")
        carrier_count = content.count("option 'carrier'")
        plmn_count = content.count("option 'plmn'")
        auto_apn_count = content.count("config feat 'auto_apn'")
        
        print(f"文件: {file_path}")
        print(f"总行数: {len(lines)}")
        print(f"总字符数: {len(content)}")
        print(f"匿名APN配置块数量: {config_count}")
        print(f"option行数量: {option_count}")
        print(f"carrier字段数量: {carrier_count}")
        print(f"plmn字段数量: {plmn_count}")
        print(f"auto_apn配置块数量: {auto_apn_count}")
        
        # 提取auto_apn配置信息
        auto_apn_info = {}
        for line in lines:
            if "option 'session_count'" in line:
                auto_apn_info['session_count'] = line.split("'")[3]
            elif "option 'session_type'" in line:
                auto_apn_info['session_type'] = line.split("'")[3]
            elif "option 'generated_time'" in line:
                auto_apn_info['generated_time'] = line.split("'")[3]
        
        print("\\nauto_apn配置信息:")
        for key, value in auto_apn_info.items():
            print(f"  {key}: {value}")
        
        # 统计各运营商的配置数量
        carriers = {}
        plmns = {}
        
        for line in lines:
            if "option 'carrier'" in line:
                carrier = line.split("'")[3]
                carriers[carrier] = carriers.get(carrier, 0) + 1
            elif "option 'plmn'" in line:
                plmn = line.split("'")[3]
                plmns[plmn] = plmns.get(plmn, 0) + 1
        
        print("\\n运营商分布:")
        for carrier, count in sorted(carriers.items()):
            print(f"  {carrier}: {count} 个配置")
        
        print("\\nPLMN分布:")
        for plmn, count in sorted(plmns.items()):
            print(f"  {plmn}: {count} 个配置")
        
        # 验证匿名session格式
        print("\\n格式验证:")
        named_sessions = content.count("config 'apn' 'apn_")
        if named_sessions > 0:
            print(f"  ⚠️ 发现 {named_sessions} 个命名session（应为0）")
        else:
            print("  ✅ 所有APN配置都使用匿名session格式")
        
        # 验证session_count是否与实际匹配
        declared_count = int(auto_apn_info.get('session_count', 0))
        if declared_count == config_count:
            print(f"  ✅ session_count ({declared_count}) 与实际APN配置数量匹配")
        else:
            print(f"  ⚠️ session_count ({declared_count}) 与实际APN配置数量 ({config_count}) 不匹配")
        
        # 显示部分配置示例
        print("\\n匿名session配置示例:")
        current_config = {}
        config_counter = 0
        
        for line in lines:
            if line.startswith("config 'apn'"):
                if current_config and config_counter < 3:  # 只显示前3个
                    config_counter += 1
                    print(f"\\n配置 #{config_counter}:")
                    print(f"  运营商: {current_config.get('carrier', 'N/A')}")
                    print(f"  配置名: {current_config.get('profile_name', 'N/A')}")
                    print(f"  APN: {current_config.get('name', 'N/A')}")
                    print(f"  PLMN: {current_config.get('plmn', 'N/A')}")
                    print(f"  认证: {current_config.get('auth', 'N/A')}")
                current_config = {}
            elif line.strip().startswith("option "):
                parts = line.strip().split("'")
                if len(parts) >= 4:
                    key = parts[1]
                    value = parts[3]
                    current_config[key] = value
        
        print("\\n✅ 匿名session UCI配置文件验证完成！")
        print(f"成功转换了 {config_count} 个匿名APN配置，覆盖 {len(carriers)} 个运营商")
        
    except Exception as e:
        print(f"验证失败: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    validate_anonymous_uci_file("apn_config.uci")